package _20250305;

import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.function.Consumer;

public class MyThread3 {
    /**
     *  题目：实现一个简单的生产者 - 消费者模型。生产者线程不断生成随机整数并放入一个固定大小为 5 的数组中，
     *  消费者线程不断从数组中取出整数并打印。要求使用synchronized关键字实现线程同步，防止数组越界和数据竞争。
     */
    //固定属猪
    private static final int[] commodity=new int[5];
    private static int index=0;
    private static final Object lock=new Object();
    public static void main(String[] args) {

        Thread producer = new Thread(new Producer());
        Thread consumer= new Thread(new Consumer());
        //循环不能放在此处，因为Thread只能调用一次
            producer.start();
            consumer.start();
    }

    /**
     * 模拟产生
     */
    private static class Producer implements Runnable {
        @Override
        public void run() {
            Random random = new Random();
            int ran= 0;
            //循环需要放此处
            while (true){
                //用lock同步锁
            synchronized (lock){
            while (index==commodity.length){
                try {
                    System.out.println("生产者等待");
                    lock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
                ran= random.nextInt(100);
                commodity[index]=ran;
                index++;
                System.out.println("生产者产生了"+ran);
                lock.notify();

            //模拟产生时间
                try {
                    Thread.sleep(300);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
            }
        }
    }

    /**
     * 模拟消费
     */
    private static class Consumer implements Runnable {
        @Override
        public void run() {
            //循环开始
            while (true){
                //用lock同步锁
            synchronized (lock){
            while (index==0){
                try {
                    System.out.println("消费等待");
                    lock.wait();
                } catch (InterruptedException e) {
                    Thread.currentThread().interrupt();
                }
            }
                System.out.println("消费者消费"+ commodity[index-1]);
                commodity[index-1]=0;
                index--;
                lock.notify();
            //模拟消费时间
            try {
                Thread.sleep(300);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            }
        }}
    }
}

